﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveSweet : MonoBehaviour
{
    private GameSweets gameSweets;

    private IEnumerator moveCorutine;
    public void Awake()
    {
        gameSweets = GetComponent<GameSweets>();
        
    }

    public void move(int _x,int _y,float _t)
    {
        if (moveCorutine != null)
        {
            StopAllCoroutines();
        }
        moveCorutine = MoveCouroutine(_x, _y, _t);
        StartCoroutine(moveCorutine);
        //gameSweets.X = _x;
        //gameSweets.Y = _y;
        //gameSweets.transform.localPosition=gameSweets.gm.CorrectPosition(gameSweets.X, gameSweets.Y);
       // gameSweets.transform.position = GameManager.Instance.CorrectPosition(gameSweets.X, gameSweets.Y);
    }
    public IEnumerator MoveCouroutine(int newX,int newY,float time)
    {
        gameSweets.X = newX;  //更新位置
        gameSweets.Y = newY;

        Vector3 startPos = transform.position;
        Vector3 endPos = GameManager.Instance.CorrectPosition(newX,newY);

        for(float t = 0; t <= time; t += Time.deltaTime)
        {
            transform.position = Vector3.Lerp(startPos, endPos, t / time);
            yield return 0;   
        }//逐步移动到目标位置

        //防止位置偏差
        transform.position = endPos;
    }
}
